<template>
  <div class="roles-manage">
    <div class="page-header">
      <h1 class="page-title">角色权限管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="_id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色标识" width="150" />
        <el-table-column label="权限" min-width="300">
          <template #default="{ row }">
            <el-tag v-for="perm in row.permissions" :key="perm" size="small" style="margin-right: 5px;">
              {{ getPermissionName(perm) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="handlePermission(row)">权限</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editVisible" :title="isEdit ? '编辑角色' : '新增角色'" width="600px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色标识(英文)" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog v-model="permissionVisible" title="分配权限" width="600px">
      <div v-if="currentRow" class="permission-content">
        <el-alert title="角色信息" type="info" :closable="false" style="margin-bottom: 20px;">
          <p>角色名称: {{ currentRow.name }}</p>
          <p>角色标识: {{ currentRow.code }}</p>
        </el-alert>
        
        <el-tree
          ref="permissionTree"
          :data="permissionTreeData"
          show-checkbox
          node-key="id"
          :default-checked-keys="currentRow.permissions"
          :props="{ children: 'children', label: 'label' }"
        />
      </div>
      <template #footer>
        <el-button @click="permissionVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPermission" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getRolesList, deleteRole, createRole, updateRole, updateRolePermissions } from '@/api/admin'

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const editVisible = ref(false)
const permissionVisible = ref(false)
const isEdit = ref(false)
const currentRow = ref<any>(null)
const formRef = ref()
const permissionTree = ref()

const searchForm = reactive({})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const formData = reactive({
  name: '',
  code: '',
  description: '',
  status: 1
})

const rules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色标识', trigger: 'blur' }]
}

// 权限树数据
const permissionTreeData = [
  {
    id: 'dashboard',
    label: '数据大屏',
    children: [
      { id: 'dashboard.view', label: '查看数据' }
    ]
  },
  {
    id: 'content',
    label: '内容管理',
    children: [
      {
        id: 'notes',
        label: '游记管理',
        children: [
          { id: 'notes.view', label: '查看' },
          { id: 'notes.create', label: '新增' },
          { id: 'notes.edit', label: '编辑' },
          { id: 'notes.delete', label: '删除' }
        ]
      },
      {
        id: 'guides',
        label: '攻略管理',
        children: [
          { id: 'guides.view', label: '查看' },
          { id: 'guides.create', label: '新增' },
          { id: 'guides.edit', label: '编辑' },
          { id: 'guides.delete', label: '删除' }
        ]
      },
      {
        id: 'qa',
        label: '问答管理',
        children: [
          { id: 'qa.view', label: '查看' },
          { id: 'qa.create', label: '新增' },
          { id: 'qa.edit', label: '编辑' },
          { id: 'qa.delete', label: '删除' }
        ]
      }
    ]
  },
  {
    id: 'users',
    label: '用户管理',
    children: [
      { id: 'users.view', label: '查看' },
      { id: 'users.edit', label: '编辑' },
      { id: 'users.delete', label: '删除' }
    ]
  },
  {
    id: 'roles',
    label: '角色权限',
    children: [
      { id: 'roles.view', label: '查看' },
      { id: 'roles.create', label: '新增' },
      { id: 'roles.edit', label: '编辑' },
      { id: 'roles.delete', label: '删除' },
      { id: 'roles.permission', label: '分配权限' }
    ]
  },
  {
    id: 'system',
    label: '系统管理',
    children: [
      { id: 'system.settings', label: '系统设置' }
    ]
  }
]

// 获取权限名称
const getPermissionName = (permCode: string) => {
  const findLabel = (data: any[], code: string): string => {
    for (const item of data) {
      if (item.id === code) return item.label
      if (item.children) {
        const found = findLabel(item.children, code)
        if (found) return found
      }
    }
    return code
  }
  return findLabel(permissionTreeData, permCode)
}

const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    const res = await getRolesList(params)
    tableData.value = res.data || []
    pagination.total = res.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    status: 1
  })
  editVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  currentRow.value = row
  Object.assign(formData, {
    name: row.name,
    code: row.code,
    description: row.description,
    status: row.status
  })
  editVisible.value = true
}

const handlePermission = (row: any) => {
  currentRow.value = row
  permissionVisible.value = true
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除该角色吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole(row._id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          await updateRole(currentRow.value._id, formData)
          ElMessage.success('更新成功')
        } else {
          await createRole(formData)
          ElMessage.success('创建成功')
        }
        editVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleSubmitPermission = async () => {
  if (!permissionTree.value) return
  
  const checkedKeys = permissionTree.value.getCheckedKeys()
  const halfCheckedKeys = permissionTree.value.getHalfCheckedKeys()
  const permissions = [...checkedKeys, ...halfCheckedKeys]
  
  submitLoading.value = true
  try {
    await updateRolePermissions(currentRow.value._id, permissions)
    ElMessage.success('权限分配成功')
    permissionVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

const formatTime = (timestamp: any) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.roles-manage {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .permission-content {
    p {
      margin: 5px 0;
      font-size: 14px;
    }
  }
}
</style>

